using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using SciptableObject;
using Script.Utilities;
using UnityEngine;
using Utilities;
using Debug = UnityEngine.Debug;
using EventHandler = Utilities.EventHandler;
using Random = UnityEngine.Random;

public class MiniPeopleEventsManager : MonoBehaviour
{
    
    private List<MiniPeopleRequestEvent> currentEventsList; //当前的事件列表
    private Dictionary<MiniPeopleRequestEvent,Coroutine> currentEventsDic; //当前的事件字典（事件-协程）
    [SerializeField]private MiniPeopleRequestEventListSO eventListSO;

    private void Awake()
    {
        currentEventsDic = new Dictionary<MiniPeopleRequestEvent, Coroutine>();
        currentEventsList = new List<MiniPeopleRequestEvent>();
    }

    private void Start()
    {
        StartCoroutine(RandomTimeToCreateEvent());
    }

    private void OnEnable()
    {
        EventHandler.OnWeatherActivate += GetEventSloveType;
    }

    private void OnDisable()
    {
        EventHandler.OnWeatherActivate -= GetEventSloveType;
    }
    /// <summary>
    /// 监听使用的卡片的类型
    /// </summary>
    /// <param name="type"></param>
    private void GetEventSloveType(MiniPeopleEventType type)
    {
      var x =  currentEventsList.Find(i => i.eventType == type);
      if (x != null)
      {
          if (currentEventsDic.ContainsKey(x))
          {
              MiniPeopleManager.Instance.StopEvent(x);
              StopCoroutine(currentEventsDic[x]);
              currentEventsDic.Remove(x);
              currentEventsList.Remove(x);
              SentEventData(x.rewordList,true);
              Debug.Log(x.eventDescribe+"事件完成");
          }
      }
    }
    
    /// <summary>
    /// 从数据库中随机创建一个事件
    /// </summary>
    public void CreateEvent()
    {
        int flag = Random.Range(0, eventListSO.eventList.Count());
        MiniPeopleRequestEvent minievent = new MiniPeopleRequestEvent();
        minievent = eventListSO.eventList[flag];
        if (currentEventsDic.ContainsKey(minievent)) return;
        var s = minievent.eventDurationTime;
        minievent.eventDurationTime *= PlayerSetting.difficulty ? 2 : 1;
        var coroutine =  StartCoroutine(StartEvent(minievent));
        minievent.eventDurationTime = s;
        currentEventsDic.Add(minievent,coroutine);
        currentEventsList.Add(minievent);
    }
    /// <summary>
    /// 启动事件,可以自动处理奖惩
    /// </summary>
    /// <param name="miniPeopletEvent">需要启动的事件</param>
    /// <returns></returns>
    IEnumerator StartEvent(MiniPeopleRequestEvent miniPeopletEvent)
    {
        EventHandler.CallMiniPeopleSpeek(miniPeopletEvent);
        yield return new WaitForSeconds(miniPeopletEvent.eventDurationTime);
        SentEventData(miniPeopletEvent.punishList,false);
        currentEventsList.Remove(miniPeopletEvent);
        currentEventsDic.Remove(miniPeopletEvent);
    }

    #region 随机生成事件
    //随机生成事件
    IEnumerator RandomTimeToCreateEvent()
    {
        while (true)
        {
            var relax = MiniPeopleManager.Instance.idleMiniPeople.Count;
            var bussy = MiniPeopleManager.Instance.busyMiniPeople.Count;
            yield return new WaitForSeconds(Random.Range(5, 10));//生成事件频率
            int count = GetMappedValue(bussy+relax);
            count = Random.Range(1, count);
            for (int i = 0; i < count; i++)
            {
                yield return new WaitForSeconds(0.1f);
                if (currentEventsList.Count < 6 && relax > 0)
                {
                    CreateEvent();
                    yield return new WaitForSeconds(Random.Range(1f, 2f));
                }
                else
                {
                    break;
                }
            }
        }
    }
    private int GetMappedValue(int input)
    {
        if (input < 6) return 1;
        if (input < 16) return 2;
        if (input < 28) return 3;
        if (input < 38) return 4;
        if (input < 46) return 5;
        return 6; // 默认返回6
    }
    #endregion
    
    /// <summary>
    /// 惩罚数值
    /// </summary>
    /// <param name="dataList"></param>
    /// <param name="flag">True:奖励，False:惩罚</param>
    public void SentEventData(List<EventRewordData> dataList,bool flag)
    {
        
        EventHandler.CallGameDataValueSend(dataList,flag);
    }
}
